import {
  View,
  StyleSheet,
  Text,
  TouchableOpacity,
  ImageBackground,
} from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
import {TextInput} from 'react-native-paper';
import React, {useMemo, useState} from 'react';
import {Formik} from 'formik';
import * as Yup from 'yup';
import {StackActions} from '@react-navigation/native';
import {encrypt} from 'utils/encrypt';
import {useAppDispatch} from 'app/store';
import {getToken} from 'app/modules/user';
import useDimensions from 'hooks/useDimensions';
export default ({navigation}: RootStackScreenProps<'login'>) => {
  const hp = useDimensions();
  const [visible, setVisible] = useState(true);
  const dispatch = useAppDispatch();
  const validationSchema = Yup.object().shape({
    username: Yup.string().required('请输入账号'),
    password: Yup.string().required('请输入密码'),
  });
  const styles = useMemo(() => {
    return StyleSheet.create({
      container: {
        alignItems: 'center',
        width: 440 * hp,
      },
      button: {
        height: 60 * hp,
        borderRadius: 12 * hp,
        borderWidth: 1,
        borderColor: 'rgba(0,0,0,0.08)',
        width: '100%',
      },
      title: {
        fontSize: 36 * hp,
        fontWeight: '700',
        color: '#FFFFFF',
        marginBottom: 64 * hp,
      },
      textInput: {
        width: 440 * hp,
        height: 64 * hp,
      },
      errors: {
        color: 'red',
        position: 'absolute',
        top: 64 * hp,
      },
    });
  }, []);
  return (
    <ImageBackground
      source={require('../../assets/Images/pic_bg.png')}
      style={{
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
        position: 'relative',
      }}>
      <View
        style={{
          backgroundColor: 'rgba(0,0,0,0.4)',
          position: 'absolute',
          width: '100%',
          height: '100%',
        }}
      />
      <View style={styles.container}>
        <Text style={styles.title}>消防作战指挥平台</Text>
        <Formik
          onSubmit={values => console.log(values)}
          validationSchema={validationSchema}
          validateOnBlur={true}
          validateOnChange={false}
          initialValues={{
            username: '',
            password: '',
          }}>
          {formik => {
            return (
              <>
                <View>
                  <TextInput
                    mode="outlined"
                    placeholder="请输入账号"
                    onChangeText={formik.handleChange('username')}
                    style={[
                      styles.textInput,
                      {
                        marginBottom: 48 * hp,
                      },
                    ]}
                  />
                  {formik.errors.username && (
                    <Text style={styles.errors}>{formik.errors.username}</Text>
                  )}
                </View>
                <View>
                  <TextInput
                    mode="outlined"
                    placeholder="请输入密码"
                    style={[
                      styles.textInput,
                      {
                        marginBottom: 48 * hp,
                        position: 'relative',
                      },
                    ]}
                    secureTextEntry={visible}
                    onChangeText={formik.handleChange('password')}
                    right={
                      <TextInput.Icon
                        onPress={() => {
                          setVisible(!visible);
                        }}
                        icon={!visible ? 'eye-off' : 'eye'}
                      />
                    }
                  />
                  {formik.errors.password && (
                    <Text style={styles.errors}>{formik.errors.password}</Text>
                  )}
                </View>
                <LinearGradient
                  useAngle
                  colors={['#3779FF', '#0A59F7']}
                  style={styles.button}
                  angle={135}>
                  <TouchableOpacity
                    onPress={() => {
                      formik.validateForm().then(async data => {
                        if (Object.keys(data).length > 0) {
                          setTimeout(() => {
                            formik.setErrors({});
                          }, 3000);
                        } else {
                          const {password, username} = formik.values;
                          const passwordRSA = await encrypt(password);
                          dispatch(getToken({username, password: passwordRSA}))
                            .unwrap()
                            .then(() => {
                              navigation.dispatch(StackActions.push('tabbar'));
                            });
                        }
                      });
                    }}>
                    <Text
                      style={{
                        textAlign: 'center',
                        lineHeight: 60 * hp,
                        fontSize: 22 * hp,
                        fontWeight: '500',
                        color: '#FFFFFF',
                      }}>
                      登录
                    </Text>
                  </TouchableOpacity>
                </LinearGradient>
              </>
            );
          }}
        </Formik>
      </View>
    </ImageBackground>
  );
};
